<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单搜索" prop="skuName">
        <el-input v-model="queryParams.skuName" placeholder="请输入商品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="daterange" value-format="YYYY-MM-DD"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="id" width="50" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="订单金额" align="center" prop="amount" />
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="getOrderInfo(scope.row)"
            v-hasPermi="['manage:order:edit']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 订单详情窗口 -->
    <el-dialog title="订单详情" v-model="detailOpen" width="800px" append-to-body>
      <!-- 替换原有的订单详情表单部分 -->
      <el-form ref="orderRef" :model="form" label-width="80px" label-position="left">
        <el-row :gutter="20">
          <!-- 订单编号 -->
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" disabled />
            </el-form-item>
          </el-col>

          <!-- 商品名称 -->
          <el-col :span="12">
            <el-form-item label="商品名称" prop="skuName">
              <el-input v-model="form.skuName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 订单金额 -->
          <el-col :span="12">
            <el-form-item label="订单金额" prop="amount">
              <el-input v-model="form.amount" disabled />
            </el-form-item>
          </el-col>

          <!-- 订单状态 -->
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <dict-tag :options="order_status" :value="form.status" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 设备编号 -->
          <el-col :span="12">
            <el-form-item label="设备编号" prop="innerCode">
              <el-input v-model="form.innerCode" disabled />
            </el-form-item>
          </el-col>

          <!-- 设备地址 -->
          <el-col :span="12">
            <el-form-item label="设备地址" prop="addr">
              <el-input v-model="form.addr" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 创建时间 -->
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <div>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
            </el-form-item>
          </el-col>

          <!-- 完成时间 -->
          <el-col :span="12">
            <el-form-item label="完成时间" prop="updateTime">
              <div>{{ parseTime(form.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.status == 1">
          <!-- 支付方式 -->
          <el-col :span="12">
            <el-form-item label="支付方式" prop="payType">
              <div>{{ form.payType === 'wxpay' ? '微信' : '支付宝' }}</div>
            </el-form-item>
          </el-col>

          <!-- 交易单号 -->
          <el-col :span="12">
            <el-form-item label="交易单号" prop="thirdNo">
              <el-input v-model="form.thirdNo" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作 -->
        <el-row :gutter="20" v-if="form.status == 1 || form.status == 0">
          <el-col :span="12">
            <el-form-item label="操作">
              <el-button type="primary" @click="handleRefund(form.id)" v-if="form.status == 1">退款</el-button>
              <el-button type="primary" @click="handleCloseOrder(form.id)" v-if="form.status == 0">关闭订单</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮 -->
      <template #footer>
        <el-button @click="detailOpen = false">取消</el-button>
        <el-button type="primary" @click="detailOpen = false">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/manage/order";

const { proxy } = getCurrentInstance();
const { pay_status, order_status } = proxy.useDict('pay_status', 'order_status');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    skuName: null,
    createTime: null,
    beginTime: null,
    endTime: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  // 深拷贝查询参数
  let params = { ...queryParams.value };
  // 处理日期范围参数，将createTime转换为beginTime和endTime
  if (params.createTime && params.createTime.length === 2) {
    params.beginTime = params.createTime[0];
    params.endTime = params.createTime[1];
    // 删除createTime属性，避免传递给后端
    delete params.createTime;
  }
  listOrder(params).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    thirdNo: null,
    innerCode: null,
    channelCode: null,
    skuId: null,
    skuName: null,
    classId: null,
    status: null,
    amount: null,
    price: null,
    payType: null,
    payStatus: null,
    bill: null,
    addr: null,
    regionId: null,
    regionName: null,
    businessType: null,
    partnerId: null,
    openId: null,
    nodeId: null,
    nodeName: null,
    cancelDesc: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单管理";
  });
}

const detailOpen = ref(false);
function getOrderInfo(row) {
  const _id = row.id
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    detailOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 取消订单 */
function handleCloseOrder(id) {
  form.value.id = id
  form.value.status = 4
  updateOrder(form.value).then(() => {
    proxy.$modal.msgSuccess("已取消订单");
    detailOpen.value = false
    getList();
  })
}

function handleRefund(id) {
  form.value.id = id
  form.value.status = 4
  form.value.payStatus = 2
  updateOrder(form.value).then(() => {
    proxy.$modal.msgSuccess("已退款");
    detailOpen.value = false
    getList();
  })
}

getList();
</script>
